package thread.waitnotifypackage;

import java.util.Queue;
import java.util.Random;

public class Consumer extends Thread {
    String consumerName;
    int maxSize;
    private final Queue<Integer> queue;

    public Consumer(Queue<Integer> queue, String consumerName, int maxSize) {
        super(consumerName);
        this.queue = queue;
        this.consumerName = consumerName;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (queue) {
                System.out.println("queue: " + queue);

                if (queue.size() == 0) {
                    try {
                        System.out.println("queue is empty, the consumer " + consumerName + " is waiting");
                        queue.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                int x = queue.poll();
                System.out.println("[" + consumerName + "]" + " consuming value:" + x);
                queue.notifyAll();

                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
